package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserLoginDTO;
import cn.tedu.weibo.pojo.dto.UserRegDTO;
import cn.tedu.weibo.pojo.vo.UserVO;
import cn.tedu.weibo.pojo.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    public int addUser(@RequestBody UserRegDTO userRegDTO){
        System.out.println(userRegDTO);
        //验证是否为重复的用户
        if(userMapper.findByUsername(userRegDTO.getUsername())!=null){
            return 2;
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;
    }
    @PostMapping("/login")
    public  int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){
       User user= userMapper.findByUsername(userLoginDTO.getUsername());
       if (user!=null){
           if (user.getPassword().equals(userLoginDTO.getPassword())){
               //将当前用户信息存入session对象
               session.setAttribute("user",user);
               return 1;
           }else {
               return 2;
           }
       }else {
           return 3;

       }
    }

    @GetMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        //该方法无法单独得知此用户是否登录过,要联合login方法
        User user = (User) session.getAttribute("user");
        System.out.println("当前登录用户信息是:"+user);
        if (user==null){
            return null;
        }
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user,vo);
        return vo;
    }

    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
